package cn.xorange.commons.security.exception;

import cn.xorange.commons.security.entity.SecurityTenant;
import lombok.Getter;
import org.springframework.security.core.AuthenticationException;

import java.io.Serializable;
import java.util.List;

/**
 * @author : yangjian
 * date : 2023/11/25
 * description :
 */
@Getter
public class SecurityException extends AuthenticationException {

    private final Integer status;
    private final Integer code;
    private Serializable data;

    public SecurityException(SecurityErrorCode code) {
        super(code.getMsg());
        this.status = code.getStatus();
        this.code = code.getCode();
    }

    public SecurityException(Integer status, Integer code, String msg){
        super(msg);
        this.status = status;
        this.code = code;
    }

    SecurityException(SecurityErrorCode code, Serializable data){
        super(code.getMsg());
        this.status = code.getStatus();
        this.code = code.getCode();
        this.data = data;
    }

    public static SecurityException showTenantLst(List<SecurityTenant> tenantList){
        return new SecurityException(SecurityErrorCode.SUCCESS,(Serializable) tenantList);
    }
    public static SecurityException systemError(String msg){
        SecurityErrorCode code = SecurityErrorCode.ERROR;
        code.setMsg(msg);
        return new SecurityException(code);
    }

    /** 登录处理器未找到 */
    public static SecurityException loginHandlerNotFound(){
        return new SecurityException(SecurityErrorCode.LOGIN_HANDLER_NOT_FOUND);
    }

    public static SecurityException tenantNotFoundException(){
        return new SecurityException(SecurityErrorCode.TENANT_NOT_FOUND_EXCEPTION);
    }

    public static SecurityException userOrPwdError(){
        return new SecurityException(SecurityErrorCode.AUTH_USERNAME_OR_PWD_ERROR);
    }

    /** 无效token 过期、无效、伪造 401 */
    public static SecurityException authUnauthorized(){
        return new SecurityException(SecurityErrorCode.AUTH_TOKEN_UNAUTHORIZED);
    }

    /** 403 **/
    public static SecurityException authForbidden(String msg){
        SecurityErrorCode code = SecurityErrorCode.AUTH_TOKEN_FORBIDDEN;
        code.setMsg(msg);
        return new SecurityException(code);
    }

    /**
     * 限流拦截
     * @return
     */
    public static SecurityException interceptRateLimiter(){
        return new SecurityException(SecurityErrorCode.INTERCEPT_RATE_LIMITER);
    }
}
